//
//  HZL_FourthMainViewController.m
//  B_Project
//
//  Created by 胡佳俊 on 15/11/24.
//  Copyright © 2015年 HZL. All rights reserved.
//

#import "HZL_FourthMainViewController.h"
#import "HZL_NetworkingHandle.h"
#import "HZL_FourthTableViewCell.h"
#import "HZL_FourthViewModel.h"

#import "HZL_FourthCollectionViewCell.h"
#import "RESideMenu.h"
@interface HZL_FourthMainViewController ()<UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *sectionArr;
@property (nonatomic, strong)NSMutableArray *cellArr;
@property (nonatomic, strong)UICollectionView *collectionView;
//添加手势
@property (nonatomic, strong)UITapGestureRecognizer *tap;
//@property (nonatomic, assign)NSInteger index;

@property (nonatomic, strong)NSIndexPath *index;
//清扫手势
@property (nonatomic, strong)UISwipeGestureRecognizer *swipe;
//tap
@property (nonatomic, strong)UITapGestureRecognizer *tapVideo;
@property (nonatomic, assign) CGFloat y;

// 刷新
@property (nonatomic, assign) NSInteger MJI;
@property (nonatomic, assign) BOOL isRefresh;
@property (nonatomic, retain) MJRefreshAutoStateFooter *footer;
@end

@implementation HZL_FourthMainViewController

- (void)viewDidAppear:(BOOL)animated
{
    self.hidesBottomBarWhenPushed = YES;
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.hidesBottomBarWhenPushed = YES;
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-liebiao"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    
    self.sectionArr = [NSMutableArray array];
    [self creatTableAndCollectionView];
    [self getData];
    
    [self loadMBProgress];
}
- (BOOL)judge
{
//    [self.collectionView scrollToItemAtIndexPath:self.indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    static BOOL isExit = NO;
    isExit = !isExit;
    return isExit;
}
#pragma mark - 获取数据
- (void)getData
{
    
    // 获取当前日期
    NSDate *senddate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMdd"];
    NSString *locationString=[dateformatter stringFromDate:senddate];
    NSString *path = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/feed?num=10&date=%@&vc=125&u=d5639e818ec69cfccfee81bbb77d9bbceb9658f4&v=1.8.1&f=iphone", locationString];
    
    [HZL_NetworkingHandle getUrl:path cookie:nil result:^(id r) {
        
        self.sectionArr = r[@"dailyList"];
        [self.hud removeFromSuperview];
        [self.tableView reloadData];

        [self.collectionView reloadData];
    }];
}
#pragma mark - 创建tableview And collectionview
- (void)creatTableAndCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(VIEW_WIDTH, VIEW_HEIGHT - 64 - 49);
    layout.minimumLineSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, VIEW_WIDTH, VIEW_HEIGHT) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass: [HZL_FourthCollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    // 注册头部分区
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.view addSubview:self.collectionView];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, VIEW_WIDTH, VIEW_HEIGHT - 64) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    
}
#pragma mark - collectionview协议方法
//section个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.sectionArr.count;
}

// 自定义分组
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, -20, VIEW_WIDTH, 100)];
    headerView.backgroundColor = [UIColor whiteColor];
    // 标题
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, VIEW_WIDTH, 30)];
    NSString *s = self.sectionArr[section][@"date"]; //对应21:00
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:[s doubleValue]/1000];
//    NSLog(@"dddd:%@",d); //2011-01-18 13:00:00 +0000
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSString *showtimeNew = [formatter1 stringFromDate:d];
    NSString *str = [showtimeNew substringWithRange:NSMakeRange(5, 6)];
    titleLabel.font = [UIFont fontWithName:@"GillSans-UltraBold" size:21];
//    titleLabel.font = [UIFont systemFontOfSize:20];
    titleLabel.text = str;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [headerView addSubview:titleLabel];
    return headerView;
    
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%ld, %ld", indexPath.item, indexPath.section);
}
//cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSArray *arr = self.sectionArr[section][@"videoList"];
    return arr.count;
}
//重用item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HZL_FourthCollectionViewCell *item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    
    NSMutableArray *cellArr = self.sectionArr[indexPath.section][@"videoList"];
    self.cellArr = [HZL_FourthViewModel transformWithArray:cellArr];
    self.index = indexPath;
    item.collectionModel = self.cellArr[indexPath.row];
    [item.swip addTarget:self action:@selector(swipeAction:)];
    
    return item;
}

#pragma mark - swipe方法
- (void)swipeAction:(UISwipeGestureRecognizer *)swipe
{
    if (swipe.direction == UISwipeGestureRecognizerDirectionUp) {
        
        [UIView transitionFromView:self.collectionView toView:self.tableView duration:1 options:UIViewAnimationOptionTransitionCrossDissolve completion:^(BOOL finished) {
            [self judge];
        }];
    }
    [self.tableView scrollToRowAtIndexPath:self.index atScrollPosition:UITableViewScrollPositionNone animated:NO];
}
#pragma mark - tableview协议方法
//section个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.sectionArr.count;
}
//section高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}
#pragma mark - cell个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = self.sectionArr[section][@"videoList"];
    return arr.count;
}

#pragma mark - 重用cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HZL_FourthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[HZL_FourthTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    NSMutableArray *cellArr = self.sectionArr[indexPath.section][@"videoList"];
    self.cellArr = [HZL_FourthViewModel transformWithArray:cellArr];
    cell.model = self.cellArr[indexPath.row];

    return cell;
}
#pragma mark - cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (VIEW_HEIGHT) / 2.8;
}
//select
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    self.hidesBottomBarWhenPushed = YES;
    [UIView transitionFromView:self.tableView toView:self.collectionView duration:1 options:UIViewAnimationOptionTransitionCrossDissolve completion:^(BOOL finished) {
        [self judge];
        [self.collectionView reloadData];
    }];
}

#pragma mark - scrollview的协议方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableView) {
        CGFloat sectionHeaderHeight = 50.0;
        if(scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0){
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        }else if(scrollView.contentOffset.y >= sectionHeaderHeight){
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
